<?php
/**
 * （Logic）每日库存统计(按平台SKU)（amazon每日库存记录）
 */

namespace App\Logic\Amazon\Statistics;

use App\Models\Amazon\FBAMYIInventory;
use App\Models\Basics\AmazonCountry;
use App\Models\Basics\SysArea;
use App\Models\Basics\SysCountry;
use App\Models\Basics\SysICountry;
use App\Models\Product\ProductAmazonSku;
use App\Models\Amazon\DailyInventory as ADailyInventory;
use Illuminate\Support\Facades\DB;
class DailyInventory
{
    /**
     * Amazon每日库存统计(平台SKU)
     * @param int $day
     */
    public static function init($day = 0){
        try{
            DB::beginTransaction();
            $sku = [];
            $fanEUSku = [];
            $countryIdFR = SysCountry::getIdByCountry('FR');
            $countryIdDE = SysCountry::getIdByCountry('DE');
            $countryIdUK = SysCountry::getIdByCountry('UK');
            $country = AmazonCountry::options(['fan_eu' => 1]);
            $countryIdsForFanEU = array_keys($country->toArray());
            $euAreaId = SysArea::getSysAreaIdByArea('EU');
            $countryIdsForEU = SysICountry::getCountryIdsByAreaId($euAreaId)->toArray();
            $countryIdsForEUNoTotalInventory = SysICountry::getEuCountryIdsForNoTotalInventory($euAreaId)->toArray();
            $countryIdsForNaNoTotalInventory = SysICountry::getNaCountryIdsForNoTotalInventory()->toArray();
            $date = date('Y-m-d',strtotime("-$day days"));

            //fba库存报告（每日）
            FBAMYIInventory::query()->orderBy('created_at')
                ->chunk(800, function ($items) use (&$sku,&$fanEUSku,$countryIdsForNaNoTotalInventory,$countryIdDE,$countryIdsForFanEU,$countryIdsForEUNoTotalInventory,$countryIdsForEU,$countryIdUK,$countryIdFR,$date){
                    foreach($items as $item){
                        if(in_array($item->country_id,$countryIdsForNaNoTotalInventory)){
                            continue;
                        }
                        if(in_array($item->country_id,$countryIdsForEU)){
                            if(in_array($item->country_id,$countryIdsForEUNoTotalInventory)){
                                continue;
                            }
                            $currentCount = ProductAmazonSku::query()
                                ->where('country_id',$item->country_id)
                                ->where('seller_sku',$item->sku)
                                ->count();
                            $ukCount = ProductAmazonSku::query()
                                ->where('country_id',$countryIdUK)
                                ->where('seller_sku',$item->sku)
                                ->count();
                            if($currentCount == 0 && $ukCount > 0){
                                continue;
                            }
                            if($item->country_id == $countryIdFR){
                                if(in_array($item->sku,['38IT-AM02076','38IT-AM01347','38IT-AM03091','38IT-AM02744','38IT-AM02745','38IT-AM04206','38IT-AM02091',
                                    'AM01313-AMEU-FBA38','AM01345-AMEU-FBA38','AM04204-AMEU-FBA38','AM02747-AMEU-FBA38','AM01312-AMEU-FBA38','66IT-AM01309','66IT-AM02746',
                                    '66ES-AM01489'])){
                                    continue;
                                }
                            }
                            if($item->country_id != $countryIdDE){
                                if(in_array($item->sku,['23DE-AM01187','23DE-AM01192','23DE-AM01193','23DE-AM01313','23DE-AM01348','23DE-AM01352','23DE-AM01463','23DE-AM01464','23DE-AM02078','23DE-AM02079','23DE-AM02091','23DE-AM02092','23DE-AM02745','23DE-AM03218','23DE-AM03219','23DE-AM04204','23DE-AM04205','23DE-AM04206','23DE-N-AM01325','23DE-N-AM02082','23DE-N-AM03217','23DE-N2-AM02077'])){
                                    continue;
                                }
                            }
                        }
                        if(in_array($item->country_id,$countryIdsForFanEU)){
                            $fanKey = $item->sku.'_'.$item->fnsku.'_'.$item->asin;
                            if(!array_key_exists($fanKey,$fanEUSku)){
                                $fanEuCount = ProductAmazonSku::query()
                                    ->where('status',1)
                                    ->whereIn('country_id',$countryIdsForFanEU)
                                    ->where('seller_sku',$item->sku)
                                    ->where('fnsku',$item->fnsku)
                                    ->where('child_asin',$item->asin)
                                    ->where('fan_eu',1)
                                    ->count();
                                $fanEUSku[$fanKey] = $fanEuCount > 0 ? true : false;
                            }
                            if($fanEUSku[$fanKey] && ($item->country_id != $countryIdDE)){
                                continue;
                            }
                        }
                        if(!array_key_exists($item->sku,$sku)){
                            $pas = ProductAmazonSku::query()->where('seller_sku',$item->sku)->first();
                            $sku[$item->sku] = $pas->psku_id ?? 0;
                        }
                        ADailyInventory::query()->updateOrCreate(
                            [
                                're_date' => $date,
                                'country_id' => $item->country_id,
                                'sku' => $item->sku,
                            ],
                            [
                                'account_id' => $item->account_id,
                                'psku_id' => $sku[$item->sku],
                                'quantity' => $item->afn_fulfillable_quantity + $item->afn_reserved_quantity + $item->afn_researching_quantity,
                            ]
                        );
                    }
                    DB::commit();
                });
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }
}
